package Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class TestUtil {

	static Scanner scanner = new Scanner(System.in);

	/**
	 * 判断int类型输入是否合法
	 * 
	 * @return
	 */
	public static int abnormal() {
		int key = 0;
		try {
			key = Integer.parseInt(scanner.nextLine());
		} catch (Exception e) {
			System.out.println("输入错误，请重新输入：");
			abnormal();
		}
		return key;
	}

	/**
	 * 序列化
	 * 
	 * @param <T>
	 * 
	 * @param path
	 * @param list
	 */
	public static <T> void write(String path, T t) {
		try {
			FileOutputStream fo = new FileOutputStream(path);
			ObjectOutputStream os = new ObjectOutputStream(fo);

			os.writeObject(t);// 序列化，持久化

			os.close();
			fo.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 创建文件
	 * 
	 * @param name
	 */
	public static String creatPath(String file, String name) {
		File f1 = new File("d:/test/" + file);// 根目录
		if (f1.exists() == false) {// 不存在这个目录
			f1.mkdirs();
		}
		File f2 = new File(f1 + "/" + name + ".txt");
		if (f2.exists() == false) {
			try {
				f2.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return f2.getPath();
	}

	/**
	 * 反序列化
	 * 
	 * @param <T>
	 * @param path
	 * @return
	 */
	public static <T> T read(String path) {
		try {
			FileInputStream fi = new FileInputStream(path);
			ObjectInputStream os = new ObjectInputStream(fi);

			Object o = os.readObject();
			os.close();
			fi.close();
			return (T) o;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获得当前时间
	 * 
	 * @return
	 */
	public static String time() {
		long currentTime = System.currentTimeMillis();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
		Date date = new Date(currentTime);
		String time = formatter.format(date);

		return time;
	}
}
